package com.liao.excel.strategy;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.List;

@Component
public class WriteStrategy {

    public void write(String sheetName, Class<?> clazz, List<?> list, HttpServletResponse httpServletResponse,
                      ScreenValueStrategy strategy1) throws Exception {
        try (
                OutputStream screenOut = httpServletResponse.getOutputStream();
                BufferedOutputStream screenBos = new BufferedOutputStream(screenOut);
        ) {
            WriteCellStyle contentWriteCellStyle = getWriteCellStyle();
            EasyExcel.write(screenBos, clazz)
                    .registerWriteHandler(strategy1)   // 自定义单元格合并策略
                    .registerWriteHandler(new HorizontalCellStyleStrategy(null, contentWriteCellStyle))
                    .registerWriteHandler(new ExcelWidthStyleStrategy())
                    .sheet(sheetName).doWrite(list);
        }
    }

    /**
     * 设置内容的策略
     *
     * @return
     */
    public static WriteCellStyle getWriteCellStyle() {
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 设置内容水平居中对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置内容垂直居中对齐
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 自动换行
        contentWriteCellStyle.setWrapped(true);
        // 设置字体样式和大小
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteFont.setFontName("微软雅黑");
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        return contentWriteCellStyle;
    }

    /**
     * HttpServletResponse消息头参数设置
     *
     * @param httpServletResponse
     */
    public static void setHttpServletResponse(HttpServletResponse httpServletResponse, String filename) {
        httpServletResponse.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
        httpServletResponse.setContentType("application/octet-stream;charset=UTF-8");
        httpServletResponse.addHeader("Pragma", "no-cache");
        httpServletResponse.addHeader("Cache-Control", "no-cache");
    }
}